package zoo.product.controller;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import zoo.product.dao.ProductDao;
import zoo.product.domain.ProductCommand;
import zoo.util.PagingUtil;

@Controller
public class ProductListController {
	private static Log log = LogFactory.getLog(ProductListController.class);
	private int pageSize = 20;
	private int blockCount = 20;
	
	@Autowired
	private ProductDao productDao;
	
	@RequestMapping(value="/main/index.do")
	public ModelAndView process(@RequestParam(value="curentPage", defaultValue="1")int currentPage,
								@RequestParam(value="keyField", defaultValue="0")String keyField,
								@RequestParam(value="keyWord", defaultValue="0")String keyWord){
		String pagingHtml;
		
		if(log.isDebugEnabled()){
			log.debug("currentPage : " + currentPage);
			log.debug("keyField : " + keyField);
			log.debug("keyWord : " + keyWord);
		}
		
		HashMap<String,Object> map = new HashMap<String, Object>();
		map.put("keyField", keyField);
		map.put("keyWord", keyWord);
		
		//총 글의 갯수 또는 검색된 글의 갯수
		int count = productDao.getProductCount(map);
		
		PagingUtil page = new PagingUtil(keyField, keyWord, currentPage, count, blockCount, pageSize);
		pagingHtml = page.getPagingHtml().toString();
		
		map.put("start", page.getStartCount());
		map.put("end", page.getEndCount());
		
		List<ProductCommand> list = null;
		if(count > 0){
			list = productDao.getProductList(map);
		}else{
			list = Collections.emptyList();
		}
		
		//글 목록에 표시할 연번
		int number = count - (currentPage-1)*pageSize;
	
		ModelAndView mav = new ModelAndView();
		mav.setViewName("index");
		mav.addObject("count", count);
		mav.addObject("list", list);
		mav.addObject("pagingHtml", pagingHtml);
		mav.addObject("number", number);
		
		return mav;
	}
}
